﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLayer;
using EntityModels;


namespace PresentationLayer
{
    public partial class ViewEvent : AbstractPage
    {
        private Event ev = new Event();
        private User us = new User();

       

        protected void Page_Load(object sender, EventArgs e)
        {
          
            try
            {
                ev.idevent = Convert.ToInt32(Request.QueryString["id"]);
                ev = Controller.Instance.GetEvent(ev.idevent);
                us = GetUserFromCookie();
                eventName.Text = ev.name;
                User admin = Controller.Instance.GetUser(ev.eidmember);
                eventCreator.Text = admin.firstname + " " + admin.lastname;
                eventVisibility.Text = ev.visibility ? "Public Event" : "Private Event";

                List<User> attendance = Controller.Instance.GetUsers(ev, 1);
                attendance_repeater.DataSource = attendance;
                attendance_repeater.DataBind();

                if (Controller.Instance.Attending(us, ev))
                {

                    AttendingButtom.Visible = false;
                    NotAttendingButtom.Visible = false;


                    if (ev.visibility == true)
                    {
                        invitemenu.Visible = true;

                    }
                }

                if (ev.eidmember == us.idmember) { invitemenu.Visible = true; Delete.Visible = true; }


                List<Location> locations = Controller.Instance.getLocations(ev);
                List<DateOptions> dates = Controller.Instance.getDates(ev);
                List<TimeOptions> times = Controller.Instance.getTimes(ev);

                Session["Locations"] = locations;
                Session["Dates"] = dates;
                Session["Times"] = times;

                this.LocationHeader.Attributes["rowspan"] = (locations.Count + 1).ToString();
                this.DateHeader.Attributes["rowspan"] = (dates.Count + 1).ToString();
                this.TimeHeader.Attributes["rowspan"] = (times.Count + 1).ToString();





                NewTemplate master = (NewTemplate)Master;
                master.BodyTag.Attributes.Add("onload", "initializeMap();");
            }
            catch (FormatException)
            {
                errorMessage.InnerHtml = "Wrong URL";
            }
            catch (Exception ex)
            {
                errorMessage.InnerHtml = ex.Message;
            }
        }
        protected void Invite (object sender, EventArgs e)
        {

            User us = new User();
            us.username = invite_username.Text;
            if (Controller.Instance.UserExists(us))
            {
                us = Controller.Instance.GetUser(us.username);
                if (Controller.Instance.Attending(us, ev))
                {
                    String scriptText = "alert('User: " + us.username + " had already been invited')";
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", scriptText, true);
                }
                else {
                    Controller.Instance.Invite(us, ev);
                    invite_username.Text="";
                    String scriptText = "alert('User with username: " + us.username + " invited.')";
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", scriptText, true);
                
                }

            }
            else {
                String scriptText = "alert('User with username: "+ us.username + " don´t exist')";
                ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", scriptText, true);
            }
           

        }

        public List<Location> GetLocations()
        {   
            
            return (List<Location>)Session["Locations"];
        }

        public List<DateOptions> GetDates()
        {

            return (List<DateOptions>)Session["Dates"];
        }

        public List<TimeOptions> GetTimes()
        {   
            
            return (List<TimeOptions>)Session["Times"];
        }


        protected void Attending(object sender, EventArgs e)
        {
            AttendingButtom.Visible = false;
            NotAttendingButtom.Visible = false;
            Controller.Instance.Attend(us, ev);
           
        }
        protected void NotAttending(object sender, EventArgs e)
        {
            AttendingButtom.Visible = false;
            NotAttendingButtom.Visible = false;
            Controller.Instance.NotAttend(us, ev);
            Response.Redirect("Profile.aspx");

        }



        private void DisableButtons(ref ListView list, String type)
        {
            for (int i = 0; i < list.Items.Count; i++)
            {
                Button b = (Button)(list.Items[i].FindControl(type));
                b.Enabled = false;
                b.Text = "You Already voted";
            }
        }

        protected void ButtonVoteLocation(object sender, EventArgs e)
        {
            Button bt = (Button)sender;
            Location lo = new Location();
            lo.idlocation = Convert.ToInt32(bt.Attributes["location"]);
            Controller.Instance.VoteLocation(us, ev, lo);
            DisableButtons(ref LocationsView, "LocationButton");
        }

        protected void ButtonVoteDate(object sender, EventArgs e)
        {
            String date;
            Button bt = (Button)sender;
            date = bt.Attributes["date"];
            Controller.Instance.VoteDate(us, ev, parseToDateTime(date));
            DisableButtons(ref DatesView, "DateButton");
        }

        protected void ButtonVoteTime(object sender, EventArgs e)
        {
            String time;
            Button bt = (Button)sender;
            time = bt.Attributes["time"];
            Controller.Instance.VoteTime(us, ev, parseToTimeSpan(time));
            DisableButtons(ref TimesView, "TimeButton");
        }
        protected void DateLabel(object sender, EventArgs e)
        {
            String date;
            Label lb = (Label)sender;
            date = lb.Attributes["date"];
            string[] aux = date.Split('/', ':',' ');
            lb.Text = aux[2] + "-" + aux[1] + "-" + aux[0];
        }


        protected void ButtonsLoad(object sender, EventArgs e)
        {
            try
            {
                Button b = (Button)sender;
                if ((Controller.Instance.LocationVoted(us, ev)) & (b.ID == "LocationButton"))
                {
                    b.Enabled = false;
                    b.Text = "You Already voted";
                }
                else if ((Controller.Instance.DateVoted(us, ev)) & (b.ID == "DateButton"))
                {

                    b.Enabled = false;
                    b.Text = "You Already voted";
                }
                else if ((Controller.Instance.TimeVoted(us, ev)) & (b.ID == "TimeButton"))
                {

                    b.Enabled = false;
                    b.Text = "You Already voted";
                }

                List<Location> locations = Controller.Instance.getLocations(ev);
                List<DateOptions> dates = Controller.Instance.getDates(ev);
                List<TimeOptions> times = Controller.Instance.getTimes(ev);
                if ((b.ID == "LocationButton") & (locations.Count == 1)) { b.Visible = false; }
                else if ((b.ID == "DateButton") & (dates.Count == 1)) { b.Visible = false; }
                else if ((b.ID == "TimeButton") & (times.Count == 1)) { b.Visible = false; }
            }
            catch (Exception)
            {
                errorMessage.InnerHtml = "Error loading event";
            }

        }

        protected void DeleteEvent(object sender, EventArgs e)
        {
            Controller.Instance.DeleteEvent(ev);
            Response.Redirect("Profile.aspx");
        }


        //Recibe a date like: yyyy-mm-dd
        public static DateTime parseToDateTime(String date)
        {
            string[] numbers = date.Split('-','/',' ');
            DateTime d = new DateTime(Convert.ToInt32(numbers[2]), Convert.ToInt32(numbers[0]), Convert.ToInt32(numbers[1]));
            return d;
        }
        //Recibe a time like: hh:mm
        public static TimeSpan parseToTimeSpan(String date)
        {
            string[] numbers = date.Split(':');
            TimeSpan t = new TimeSpan(Convert.ToInt32(numbers[0]), Convert.ToInt32(numbers[1]), 00);
            return t;
        }

        
      
    }
    


    
}


    
